// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package user_api_serv

import (
	"context"
	"strings"

	"gitcode.com/lvupclub/lvup-api/dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/user_api"
	"github.com/dchest/uniuri"
	"github.com/google/uuid"
)

func (apiImpl *UserApiImpl) loginByLocal(ctx context.Context, userName, passwd string) (*user_api.LoginResponse, error) {
	emptyInfo := &user_api.UserInfo{
		BasicInfo: &user_api.BasicUserInfo{},
	}
	userInfoItem, err := user_dao.UserInfoDao.GetByName(ctx, user_api.USER_TYPE_USER_TYPE_LOCAL, userName)
	if err != nil {
		return &user_api.LoginResponse{
			Code:     user_api.LoginResponse_CODE_WRONG_USERNAME,
			ErrMsg:   "用户不存在",
			UserInfo: emptyInfo,
		}, nil
	}
	err = user_dao.UserPasswdDao.Auth(ctx, userInfoItem.UserId, passwd)
	if err != nil {
		return &user_api.LoginResponse{
			Code:     user_api.LoginResponse_CODE_WRONG_PASSWD,
			ErrMsg:   err.Error(),
			UserInfo: emptyInfo,
		}, nil
	}

	//创建会话
	sessionId := uniuri.NewLen(32) + strings.ReplaceAll(uuid.NewString(), "-", "")
	dao.CacheDao.SetSession(ctx, &dao.SessionDbItem{
		SessionId: sessionId,
		UserId:    userInfoItem.UserId,
		UserType:  user_api.USER_TYPE_USER_TYPE_LOCAL,
	})
	return &user_api.LoginResponse{
		Code:      user_api.LoginResponse_CODE_OK,
		SessionId: sessionId,
		UserInfo:  userInfoItem.ToUserInfo(),
	}, nil
}
